package com.shengsheng.expschedule.service.mail.controller.api;

import com.shengsheng.expschedule.base.result.R;
import com.shengsheng.expschedule.base.result.ResultCodeEnum;
import com.shengsheng.expschedule.base.util.FormUtils;
import com.shengsheng.expschedule.base.util.RandomUtils;
import com.shengsheng.expschedule.service.base.exception.ExpScheduleException;
import com.shengsheng.expschedule.service.mail.service.MailService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author yuan
 * @date 2021/11/11
 */
@Api(tags = "邮件管理")
@RestController
@RequestMapping("/api/mail")
@RefreshScope
public class ApiMailController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MailService mailService;

    @ApiOperation("邮件发送")
    @GetMapping("/send/{mail}")
    public R sendMail(@ApiParam(value = "收件地址", required = true)
                      @PathVariable String mail) {
        // 校验邮箱是否合法
        if (StringUtils.isEmpty(mail) || !FormUtils.isEmail(mail))
            throw new ExpScheduleException(ResultCodeEnum.ACCOUNT_MAIL_ERROR);

        // 生成验证码
        String code = RandomUtils.getSixBitRandom();
        // 发送验证码
        try {
            mailService.sendCode(mail, "实验室在线排课系统注册验证码", code, "code.html");
        } catch (Exception e) {
            throw new ExpScheduleException(ResultCodeEnum.MAIL_SEND_ERROR);
        }
        // 将验证码存入redis缓存,五分钟有效
        redisTemplate.opsForValue().set(mail, code, 5, TimeUnit.MINUTES);

        return R.ok().message("邮件发送成功");
    }
}
